angular.module('furion.services.vcode', [])

.factory "VcodeService", ($rootScope, $timeout)->
  {
    stop_reject_flag: false

    stopReject: (usage)->
      this.stop_reject_flag = true
      this.setRejectWaitingHandler(usage, 0)

    setRejectWaiting: (usage, sec = 60)->
      this.setRejectWaitingHandler(usage, sec)
      this.rejectWaitingHandler(usage, sec)

    setRejectWaitingHandler: (usage, sec)->
      json_waiting = angular.fromJson window.localStorage.getItem('rt-vcode_reject_waiting')
      json_waiting ||= {}
      json_waiting[usage] = sec
      window.localStorage.setItem('rt-vcode_reject_waiting', angular.toJson(json_waiting))
      $rootScope.vcode_reject_waiting ||= {}
      $rootScope.vcode_reject_waiting[usage] = sec

    startRejectWaiting: (usage)->
      json_waiting = angular.fromJson window.localStorage.getItem('rt-vcode_reject_waiting')
      if json_waiting
        waiting = json_waiting[usage]
        this.rejectWaitingHandler(waiting) if waiting

    startAllRejectWaiting: ()->
      $rootScope.vcode_reject_waiting ||= {}
      json_waiting = angular.fromJson window.localStorage.getItem('rt-vcode_reject_waiting')
      if json_waiting
        for usage, sec of json_waiting
          this.rejectWaitingHandler(usage, sec)

    rejectWaitingHandler: (usage, sec)->
      this.stop_reject_flag = false
      console.debug "start vcode reject waiting: #{usage} #{sec}"
      $rootScope.vcode_reject_waiting ||= {}
      $rootScope.vcode_reject_waiting[usage] = sec
      vcode_service = this
      if sec > 0
        for i in [1..sec]
          t = 1000 * i
          past = 1
          $timeout ->
            return if vcode_service.stop_reject_flag
            s = sec - past
            if s >= 0
              vcode_service.setRejectWaitingHandler(usage, s)
              console.debug "vcode reject waiting: #{usage} #{s}"
            past += 1
          , t
      return
  }